package cn.biao.epic.sys.modular.system.service;

import cn.biao.epic.base.enmus.CommonStatus;
import cn.biao.epic.core.util.ToolUtil;
import cn.biao.epic.model.exception.ServiceException;
import cn.biao.epic.sys.core.exception.enums.BizExceptionEnum;
import cn.biao.epic.sys.modular.system.entity.Dict;
import cn.biao.epic.sys.modular.system.mapper.DictMapper;
import cn.biao.epic.sys.modular.system.model.params.DictParam;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther Uncle_Z
 * @date 2019/12/6 18:11
 * @Email:2545375@qq.com
 * @Descrition
 */
@Service
public class DictService extends ServiceImpl<DictMapper, Dict> {

    @Autowired
    private DictTypeService dictTypeService;

    /**
     * 
     * 新增
     *
     * @author uncle_z
     * @Date 2019/12/8 16:05
     * @Param [param]
     * @File DictService.java 
     */
    public void add(DictParam param) {
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.and(i -> i.eq("code", param.getCode()).or().eq("name", param.getName()))
                .and(i -> i.eq("dict_type_id", param.getDictTypeId()));
        List<Dict> dictList = this.list(dictQueryWrapper);
        if (dictList != null && dictList.size()>0) {
            throw new ServiceException(BizExceptionEnum.DICT_EXISTED);
        }

        Dict entity = getEntity(param);
        //设置状态
        entity.setStatus(CommonStatus.ENABLE.getCode());
        this.save(entity);
    }

    /**
     *
     * 删除
     *
     * @author uncle_z
     * @Date 2019/12/8 16:18
     * @Param [param]
     * @File DictService.java
     */
    public void delete(DictParam param) {

        //删除字典的所有子级
        List<Long> subIds = getSubIds(param.getDictId());
        if (subIds.size() > 0) {
            this.removeByIds(subIds);
        }

        this.removeById(getKey(param));
    }

    /**
     *
     * 更新
     *
     * @author uncle_z
     * @Date 2019/12/8 16:18
     * @Param [param]
     * @File DictService.java
     */
    public void update(DictParam param) {
        Dict oldEntity = getOldEntity(param);
        Dict newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);

        //判断编码是否重复
        QueryWrapper<Dict> wrapper = new QueryWrapper<Dict>()
                .and(i -> i.eq("code", newEntity.getCode()).or().eq("name", newEntity.getName()))
                .and(i -> i.ne("dict_id", newEntity.getDictId()))
                .and(i -> i.eq("dict_type_id", param.getDictTypeId()));
        int dicts = this.count(wrapper);
        if (dicts > 0) {
            throw new ServiceException(BizExceptionEnum.DICT_EXISTED);
        }

        //设置pids
        dictSetPids(newEntity);

        this.updateById(newEntity);
    }

    public List<Dict> findPageBySpec(DictParam param) {
        QueryWrapper<Dict> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("dict_type_id", param.getDictTypeId());

        if (ToolUtil.isNotEmpty(param.getCondition())) {
            objectQueryWrapper.and(i -> i.eq("code", param.getCondition()).or().eq("name", param.getCondition()));
        }

        objectQueryWrapper.orderByAsc("sort");

        List<Dict> list = this.list(objectQueryWrapper);

        //创建根节点
        Dict dict = new Dict();
        dict.setName("根节点");
        dict.setDictId(0L);
        dict.setParentId(-999L);
        list.add(dict);

        return list;
    }


    private Serializable getKey(DictParam param) {
        return param.getDictId();
    }

    private Dict getOldEntity(DictParam param) {
        return this.getById(getKey(param));
    }

    private Dict getEntity(DictParam param) {
        Dict entity = new Dict();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    private List<Long> getSubIds(Long dictId) {

        ArrayList<Long> longs = new ArrayList<>();

        if (ToolUtil.isEmpty(dictId)) {
            return longs;
        } else {
            List<Dict> list = this.baseMapper.likeParentIds(dictId);
            for (Dict dict : list) {
                longs.add(dict.getDictId());
            }
            return longs;
        }
    }

    private void dictSetPids(Dict param) {
        if (param.getParentId().equals(0L)) {
            param.setParentIds("[0]");
        } else {
            //获取父级的pids
            Long parentId = param.getParentId();
            Dict parent = this.getById(parentId);
            if (parent == null) {
                param.setParentIds("[0]");
            } else {
                param.setParentIds(parent.getParentIds() + "," + "[" + parentId + "]");
            }
        }
    }

}
